#include "stdinc.h"
#include "CustomMenuManager.h"
#include "wininet.h"
#include "SimpleXML.h"
#include "LogManager.h"
//#define FRAME_BUFFER_SIZE 4096


CustomMenuManager::CustomMenuManager(void)
{
	SettingsManager::getInstance()->addListener(this);
}

CustomMenuManager::~CustomMenuManager(void)
{
	clearList();
	SettingsManager::getInstance()->removeListener(this);
}

void 
CustomMenuManager::clearList()
{
    for( MenuIter i = m_menuList.begin(); i!= m_menuList.end(); ++i)
    {
        delete (*i);
    }
    m_menuList.clear();
	m_urlList.clear();
}

void CustomMenuManager::load(/* SimpleXML&*/ /*aXml*/)
{
	clearList();
	if (SETTING(USE_CUSTOM_MENU))
	{
		const string strPathURL = SETTING(CUSTOM_MENU_PATH);
		if (!strPathURL.empty())
		{
			string data;
			SimpleXML xml;
			int i = 0;
			try{
				// Download and Parse it.
				GetData(strPathURL, data);
				xml.fromXML(data);
				xml.resetCurrentChild();
				if (xml.findChild("CustomMenu"))
				{
					setTitle(xml.getChildAttrib("name"));
					xml.stepIn();
					ProcessXMLSubMenu(xml, i);
				}
			}catch(const Exception& e)
			{
				LogManager::getInstance()->message(e.getError());
				clearList();
			}
		}
	}

}
void
CustomMenuManager::ProcessXMLSubMenu(SimpleXML& xml, int& i)
{
	while(xml.findChild("MenuItem"))
	{
		string type = xml.getChildAttrib("type");
		if (!type.empty())
		{
			if (type == "menuItem")
			{
				string url = xml.getChildAttrib("link");
				string title = xml.getChildData();
				CustomMenuItem* item = new CustomMenuItem(1, i, title);
				m_urlList[i++] = url;
				m_menuList.push_back(item);
			}else if (type == "separator")
			{
				CustomMenuItem* item = new CustomMenuItem(0, 0, "");
				m_menuList.push_back(item);
			}else if (type == "submenu")
			{
				string title = xml.getChildAttrib("name");
				CustomMenuItem* item = new CustomMenuItem(2, 0, ""); // Start Submenu
				m_menuList.push_back(item);
				// Send TO iterations and get items inside.
				xml.stepIn();
				ProcessXMLSubMenu(xml, i);
				xml.stepOut();
				item = new CustomMenuItem(3, 0, title); // End Submenu
				m_menuList.push_back(item);
			}
		}
	}
}
size_t 
CustomMenuManager::GetData(string const& url, string& data)
{
	return Util::getDataFromInet(_T("CustomMenuManager::GetData"), 4096, url, data, 10000);
}

string 
CustomMenuManager::GetUrlByID(int id)
{
	if (id >-1 && id < (int)m_urlList.size())
	{
		return m_urlList[id];
	}
	return "";
}